package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithFlavors(DishDTO dishDTO) {
        // 从dishDTO中获取菜品实体类部分
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);

        // 从dishDTO中获取口味部分
        List<DishFlavor> flavors = dishDTO.getFlavors();

        // 插入一条数据到dish表，拿到返回的新插入的菜品id值
        dishMapper.insert(dish);
        long id = dish.getId();

        // 插入n条数据到dish_flavor表
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 菜品信息分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.pageQuery(dishPageQueryDTO);

        // 将List<Dish>转为List<DishVO>
        List<Dish> dishes = page.getResult();
        List<DishVO> dishVOS = BeanUtil.copyToList(dishes, DishVO.class);
        if (dishes == null || dishes.isEmpty()){
            return new PageResult(page.getTotal(), dishVOS);
        }


        // 根据dishVOS的categoryIds(分类id列表)查询category(分类表中的对应项)
        List<Category> categories = categoryMapper.selectByIds(dishVOS.stream().map(DishVO::getCategoryId).collect(Collectors.toList()));

        // 建立分类id到name的一个Map映射
        Map<Long, String> categoryId2NameMap = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));

        // 遍历dishVOS集合，设置每一项的分类名称
        dishVOS.forEach(dishVO -> {
            dishVO.setCategoryName(categoryId2NameMap.get(dishVO.getCategoryId()));
        });

        return new PageResult(page.getTotal(), dishVOS);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO selectById(Long id) {
        // 1.根据id获取dish实体类的信息
        Dish dish = dishMapper.selectById(id);

        // 2.根据dish实体类的categoryId获取categoryName(分类名称)
        Category category = categoryMapper.selectById(dish.getCategoryId());
        String categoryName = category.getName();

        // 3.根据id获取flavors(口味列表)
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(dish.getId());

        // 4.dish转dishvo
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        dishVO.setCategoryName(categoryName);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 起售或者停售菜品，停售菜品时，包含该菜品的套餐也停售
     * @param id
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startOrStop(Long id, Integer status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        // status == 1，起售菜品
        if (StatusConstant.ENABLE.equals(dish.getStatus())){
            dishMapper.update(dish);
        } else if (StatusConstant.DISABLE.equals(dish.getStatus())) {
            dishMapper.update(dish);  // 禁售菜品

            // 禁售菜品同时禁售包含该菜品的套餐
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(dish.getId());
            List<SetmealDish> setmealDishes = setmealDishMapper.selectByDishIds(dishIds);

            // 如果该菜品包含了关联的套餐，则将套餐也禁售
            if (setmealDishes != null && setmealDishes.size() > 0){
                setmealMapper.updateStatusByIds(setmealDishes.stream().map(SetmealDish::getSetmealId).collect(Collectors.toList()), StatusConstant.DISABLE);
            }
        }
    }

    /**
     * 批量删除菜品，包括菜品和口味表
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectByIds(ids);
        // 如果菜品处于起售状态则不允许删除 DISH_ON_SALE
        dishes.forEach(dish -> {
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        // 如果菜品和套餐存在关联项，则也不允许删除 DISH_BE_RELATED_BY_SETMEAL
        List<SetmealDish> setmealDishes = setmealDishMapper.selectByDishIds(ids);
        if (!setmealDishes.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除dish表里的相关项
        dishMapper.deleteByIds(ids);

        // 删除dish_flavor表的相关项
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 修改菜品，涉及菜品表和菜品口味关系表
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWithFlavors(DishDTO dishDTO) {
        // 修改菜品表
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        dishMapper.update(dish);

        // 根据dishId先将原来的dish_flavor表的表项删除
        List<Long> dishIds = new ArrayList<>();
        dishIds.add(dish.getId());
        dishFlavorMapper.deleteByDishIds(dishIds);

        // 向dish_flavor表插入新的表项
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (!dishFlavors.isEmpty() && dishFlavors != null){
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(dishFlavors);
        }

    }

    /**
     * 根据分类id查询菜品以及菜品对应的口味
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectWithFlavorsByCategoryId(Long categoryId) {
        // 根据分类id查询起售中的菜品
        Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
        List<Dish> dishes = dishMapper.selectByCondition(dish);
        List<DishVO> dishVOS = BeanUtil.copyToList(dishes, DishVO.class);
        if (dishes == null || dishes.isEmpty()){
            return dishVOS;
        }

        // 根据分类id查询分类名称
        Category category = categoryMapper.selectById(categoryId);
        String categoryName = category.getName();

        // 根据菜品id查询口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishIds(dishes.stream().map(Dish::getId).collect(Collectors.toList())); // 先一次性查出所有菜品的口味
        Map<Long, List<DishFlavor>> dishId2FlavorsMap = dishFlavors.stream().collect(Collectors.groupingBy(DishFlavor::getDishId)); // 按照菜品id进行分组

        dishVOS.forEach(dishVO -> {
            dishVO.setCategoryName(categoryName);
            dishVO.setFlavors(dishId2FlavorsMap.get(dishVO.getId()));
        });

        return dishVOS;
    }
}
